// ==UserScript==
// @name			Sector Danger Overlay
// @namespace		falcons.marknas.com
// @description		Adds sector and tile danger levels to Nav screen from recent combat logs, hacks and sightings
// @include			http://orion.pardus.at/main.php*
// @version		   	0.7.1
// ==/UserScript==

function getValidationCode(){
	if ((localStorage.getItem('alertValidation') == null) || (localStorage.getItem('alertValidation').length < 20)){
		if (localStorage.getItem('alertValidation') != null){
			localStorage.remove('dlist');
		}
		var valid = prompt('Enter validation code: ', '');
		localStorage.setItem('alertValidation', valid);
		return valid;
	}
	else return localStorage.getItem('alertValidation');
}

function setNewValidationCode(){
	var currentCode = "";
	if (localStorage.getItem('alertValidation') != null){
		currentCode = localStorage.getItem('alertValidation');
	}
	var valid = prompt('Enter validation code: ', currentCode);
	localStorage.setItem('alertValidation', valid);
}

function updateList(){
	var valid = getValidationCode();
	var uname = top.frames[1].document.getElementById('universe').getAttribute('title');
	uname = uname.substring(7);

	GM_xmlhttpRequest({
		method: "GET",
		url: "http://logger.fedfalcons.com/alerter/threat_data.php?valid="+valid+"&uname="+uname,
		onload: function(response){
			localStorage.setItem('dlist', response.responseText); 
			top.frames[2].location = "http://orion.pardus.at/main.php";
		}
	});
	var now = new Date();
	now = parseInt( now.getTime()/60000 );
	localStorage.setItem('updated', now);
}

function getFirstOtherPilot(){
	var data = document.getElementById('otherships_content');
	var player = data.innerHTML;
	var plPos = player.indexOf("scan_type=player",0) + 18;
	// Check if there's a bounty on the first player:
	if(player.indexOf("title", plPos) == plPos){
		plPos = player.indexOf("font color=", plPos) + 21; 
	}
	player = player.substring(plPos, player.indexOf("<", plPos));
	return player;
}

function sighting(){
	var snode = document.getElementById('sightdiv');
	if( snode == null )
	{
		var firstOtherPilot = '';
		var otherShips = document.getElementById('otherships');
		if(otherShips.style.display != 'none'){
			firstOtherPilot = getFirstOtherPilot();
		}
		var valid = getValidationCode();
		var uname = top.frames[1].document.getElementById('universe').getAttribute('title');
		uname = uname.substring(7);
		
		var sdiv = document.createElement('div');
		sdiv.name = 'sightdiv';
		sdiv.id = 'sightdiv';
		var sform = document.createElement('form');
		sform.name = 'sightform';
		sform.id = 'sightform';
		sform.method = 'post';
		sform.action = 'http://logger.fedfalcons.com/alerter/savesighting.php';
		sform.enctype = 'multipart/form-data';
		sform.target = '_blank';
		var sname = document.createElement('input');
		sname.name = 'sname';
		sname.id = 'sname';
		sname.type = 'text';
		sname.size = 12;
		sname.maxLength = 30;
		sname.defaultValue = firstOtherPilot;
		var ssector = document.createElement('input');
		ssector.name = 'ssector';
		ssector.id = 'ssector';
		ssector.type = 'text';
		ssector.size = 10;
		ssector.maxLength = 20;
		ssector.defaultValue = sector;
		var scoords = document.createElement('input');
		scoords.name = 'scoords';
		scoords.id = 'scoords';
		scoords.type = 'text';
		scoords.size = 7;
		scoords.maxLength = 10;
		scoords.defaultValue = cpos;
		var svalid = document.createElement('input');
		svalid.name = 'vcode';
		svalid.id = 'vcode';
		svalid.type = 'hidden';
		svalid.value = valid;
		var suname = document.createElement('input');
		suname.name = 'uname';
		suname.id = 'uname';
		suname.type = 'hidden';
		suname.value = uname;
		var ssubmit = document.createElement('input');
		ssubmit.name = 'ssubmit';
		ssubmit.id = 'ssubmit';
		ssubmit.type = 'submit';
		ssubmit.value = 'Submit';

		sform.innerHTML += ' Name: ';
		sform.appendChild(sname);
		sform.innerHTML += ' Sector: ';
		sform.appendChild(ssector);
		sform.innerHTML += ' Coords: ';
		sform.appendChild(scoords);
		sform.appendChild(svalid);
		sform.appendChild(suname);
		sform.appendChild(ssubmit);
		sdiv.appendChild(sform);
		sdiv.setAttribute("align", "center");

		danger.parentNode.appendChild(sdiv);
	}
	else snode.parentNode.removeChild(snode);
}

function resetGM(){
	var tmax = prompt('Enter Nav chart size (e.g. 7 for 7x7):', localStorage.getItem('tmax'));
	localStorage.setItem('tmax', tmax);
	var valid = prompt('Validation code (reset to 1 for new validation):', localStorage.getItem('alertValidation'));
	localStorage.setItem('alertValidation', valid);
}

if (localStorage.getItem('tmax') == null ){
	var tmax = prompt('Enter Nav chart size (e.g. 7 for 7x7):', '9');
	localStorage.setItem('tmax', tmax);
}else 
	var tmax = parseInt(localStorage.getItem('tmax'));
tmax = (tmax-1)/2;

var now = new Date();
now = parseInt( now.getTime()/60000 );

var dlist = -1;
if (localStorage.getItem('dlist') == null) 
	updateList();
else dlist = localStorage.getItem('dlist');
//alert(dlist);
if (dlist != -1)
{
	var sector = document.getElementById('sector').textContent;
	var cpos = document.getElementById('coords').textContent;
	var cx = parseInt(cpos.substring(cpos.indexOf('[')+1,cpos.indexOf(',')));
	var cy = parseInt(cpos.substring(cpos.indexOf(',')+1,cpos.indexOf(']')));
	var danger = document.createElement("div");
	var tilestr = 0;

	if (dlist.indexOf(sector) != -1) {
		var slist;
		if(dlist.indexOf('|',dlist.indexOf(sector)) != -1){
			slist = dlist.substring(dlist.indexOf(sector),dlist.indexOf('|',dlist.indexOf(sector)));
		} else {
			slist = dlist.substring(dlist.indexOf(sector));
		}
	} else slist = 0;
	
	if (slist != 0)
	{
		var clist = slist.split(';');
		var sn = clist.length-1;
		if (clist[sn] > 5)
		{
			document.getElementById('navForm').parentNode.setAttribute("style", "border:2px solid red;");

			danger.setAttribute("style", "font: bold 14px Verdana; color: red");
			danger.innerHTML = "<span title='Sector string: "+slist+"'>VERY HIGH Danger:</span> &gt;"+clist[sn]+" enemies in sector!<br>";
		}
		else if (clist[sn] > 2)
		{
			document.getElementById('navForm').parentNode.setAttribute("style", "border:2px solid #FF8000;");

			danger.setAttribute("style", "font: bold 14px Verdana; color: #FF8000");
			danger.innerHTML = "<span title='Sector string: "+slist+"'>HIGH Danger:</span> &gt;"+clist[sn]+" enemies in sector!<br>";
		}
		else
		{
			document.getElementById('navForm').parentNode.setAttribute("style", "border:2px solid yellow;'");

			danger.setAttribute("style", "font: bold 14px Verdana; color: yellow");
			danger.innerHTML = "<span title='Sector string: "+slist+"'>MEDIUM Danger:</span> &gt;"+clist[sn]+" enemies in sector!<br>";
		}
		
		var nav = document.getElementById('navarea');
		
		if (clist[sn-1] == '??') sn=sn-1;
		for(var i=1; i<sn; i++)
		{
			var cs = clist[i].split(':')[1].split(',');
			var cn = clist[i].split(':')[0];
			if ( (cs[0] >= cx-tmax && cs[0] <= cx+tmax) && (cs[1] >= cy-tmax && cs[1] <= cy+tmax) )
			{
				var navpos = nav.getElementsByTagName('tr')[cs[1]-(cy-tmax)].getElementsByTagName('td')[cs[0]-(cx-tmax)];

				if( navpos.getElementsByTagName('a')[0] )
				{
					var child = document.createElement("a");
					child.setAttribute("href", "javascript:"+navpos.getElementsByTagName('a')[0].getAttribute("onclick"));
					child.setAttribute("title", cn);
					child.setAttribute("style", "position:absolute; top:-28px; left:28px; text-decoration: none; font: bold 14px Verdana; color: red");
					child.innerHTML = "A";

					navpos.getElementsByTagName('a')[0].setAttribute("style", "position:relative;");
					navpos.getElementsByTagName('a')[0].appendChild(child);
				}
				if (cs[0] == cx && cs[1] == cy) tilestr = sector+';'+cx+','+cy;
			}
		}
	}
	else
	{
		document.getElementById('navForm').parentNode.setAttribute("style", "border:2px solid black;");

		danger.setAttribute("style", "font: bold 14px Verdana; color: #2C99EB");
		danger.innerHTML = "Low Danger!<br>";
	}
	
	danger.setAttribute("align", "center");
	document.getElementById('navForm').parentNode.parentNode.parentNode.parentNode.parentNode.appendChild(danger);

	var mainform = document.createElement('form');
	mainform.name = 'mainform';
	mainform.id = 'mainform';
	mainform.method = 'post';
	mainform.action = 'http://logger.fedfalcons.com/alerter/sightremove.php';
	mainform.enctype = 'multipart/form-data';
	mainform.target = '_blank';
	
	

	var threatbtn = document.createElement("input");
	threatbtn.setAttribute("style", "border:1px solid; margin: 4px;");
	threatbtn.setAttribute("type", "button");
	threatbtn.setAttribute("name", "threat");
	threatbtn.setAttribute("value", "Falcon Logger");
	threatbtn.setAttribute("title", "Visit the Falcon Logger for more information!");
	threatbtn.setAttribute("onclick", "window.open('http://logger.fedfalcons.com');");

	mainform.appendChild(threatbtn);

	var sightbtn = document.createElement("input");
	sightbtn.setAttribute("style", "border:1px solid; margin: 4px;");
	sightbtn.setAttribute("type", "button");
	sightbtn.setAttribute("name", "sight");
	sightbtn.setAttribute("value", "Enemy Sighting");
	sightbtn.setAttribute("title", "Upload enemy sightings if no combat or hack log exists");
	sightbtn.addEventListener("click", sighting, false);

	mainform.appendChild(sightbtn);

	var tileclear = document.getElementById('otherships');
	//if( tilestr != 0 && tileclear.style.display == 'none' )
	if( tilestr != 0)
	{
		var valid = localStorage.getItem('alertValidation');
		var uname = top.frames[1].document.getElementById('universe').getAttribute('title');
		uname = uname.substring(7);

		var remtile = document.createElement('input');
		remtile.name = 'remtile';
		remtile.id = 'remtile';
		remtile.type = 'hidden';
		remtile.value = tilestr;
		var remvalid = document.createElement('input');
		remvalid.name = 'valid';
		remvalid.id = 'valid';
		remvalid.type = 'hidden';
		remvalid.value = valid;
		var remuname = document.createElement('input');
		remuname.name = 'uname';
		remuname.id = 'uname';
		remuname.type = 'hidden';
		remuname.value = uname;
		var remsubmit = document.createElement('input');
		remsubmit.name = 'remsubmit';
		remsubmit.id = 'remsubmit';
		remsubmit.type = 'submit';
		remsubmit.setAttribute("style", "border:1px solid; margin: 4px;");
		remsubmit.title = 'Mark current tile as clear';
		remsubmit.value = 'Clear Warning';

		mainform.appendChild(remtile);
		mainform.appendChild(remvalid);
		mainform.appendChild(remuname);
		mainform.appendChild(remsubmit);
	}
	//alert(now-localStorage.getItem('updated'));
	if( (now-localStorage.getItem('updated')) > 720)
	{
		updateList();
	}
	else if( (now-localStorage.getItem('updated')) > 1)
	{
		var updbtn = document.createElement("input");
		updbtn.setAttribute("style", "border:1px solid; margin: 4px;");
		updbtn.setAttribute("type", "button");
		updbtn.setAttribute("name", "Update");
		updbtn.setAttribute("value", "Update Danger List");
		updbtn.setAttribute("title", "Update before you move into dangerous sectors.");
		updbtn.addEventListener("click", updateList, false);

		mainform.appendChild(updbtn);
	}

	var resetbtn = document.createElement("img");
	resetbtn.setAttribute("src", "http://static.pardus.at/images/info.gif");
	resetbtn.setAttribute("alt", "Reset values");
	resetbtn.setAttribute("title", "Reset values");
	resetbtn.addEventListener("click", resetGM, false);

	mainform.appendChild(resetbtn);

	danger.appendChild(mainform);
}
else
{
	var invalid = document.createElement("div");
	invalid.setAttribute("style", "position:absolute; top:150px; left:225px; text-decoration: blink; text-align: center;"+
		"font: bold 24px Verdana; color: red;");
	invalid.innerHTML = "<h1>- FEDERAL SECURITY ALERT -</h1><br><br>";
	invalid.innerHTML += "Intruder detected: Invalid Security Clearance!<br><br>";

	document.getElementsByTagName('body')[0].appendChild(invalid);

	var validdiv = document.createElement("div");
	validdiv.setAttribute("align", "center");
	var validbtn = document.createElement("input");
	validbtn.setAttribute("style", "border:1px solid; margin: 4px; color: red;")
	validbtn.setAttribute("type", "button");
	validbtn.setAttribute("name", "Validate");
	validbtn.setAttribute("value", "Re-validate Security Clearance!");
	validbtn.addEventListener("click", setNewValidationCode, false);
	validdiv.appendChild(validbtn);

	document.getElementsByTagName('body')[0].appendChild(validdiv);
}
